// Form validation utilities

export const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

export const validatePassword = (password) => {
  // Minimum 8 characters, at least one uppercase letter, one lowercase letter, one number
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/;
  return passwordRegex.test(password);
};

export const validateName = (name) => {
  // Name should be at least 2 characters and contain only letters and spaces
  const nameRegex = /^[a-zA-Z\u4e00-\u9fa5\s]{2,}$/;
  return nameRegex.test(name);
};

export const validatePhone = (phone) => {
  // Support Chinese phone numbers (11 digits starting with 1)
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

export const validateVerificationCode = (code) => {
  // Verification code should be 6 digits
  const codeRegex = /^\d{6}$/;
  return codeRegex.test(code);
};

export const generateMockVerificationCode = () => {
  // Generate a 6-digit verification code for mock purposes
  return Math.floor(100000 + Math.random() * 900000).toString();
};

export const calculatePasswordStrength = (password) => {
  let strength = 0;
  
  if (password.length >= 8) strength++;
  if (password.length >= 12) strength++;
  if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength++;
  if (password.match(/[0-9]/)) strength++;
  if (password.match(/[^a-zA-Z0-9]/)) strength++;
  
  return Math.min(strength, 4); // Cap at 4 for our UI
};

export const getPasswordStrengthText = (strength, t) => {
  switch (strength) {
    case 0:
      return { text: t('passwordStrength.veryWeak'), color: '#ef4444' };
    case 1:
      return { text: t('passwordStrength.weak'), color: '#f59e0b' };
    case 2:
      return { text: t('passwordStrength.fair'), color: '#eab308' };
    case 3:
      return { text: t('passwordStrength.strong'), color: '#22c55e' };
    case 4:
      return { text: t('passwordStrength.veryStrong'), color: '#10b981' };
    default:
      return { text: '', color: '' };
  }
};

export const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

export const throttle = (func, limit) => {
  let inThrottle;
  return function() {
    const args = arguments;
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};